﻿
<template>
    <!-- 商家用户登录 -->
    <div class="">
        <x-header :left-options="{backText: ''}" class="ret">
            <div class="retTitle">
                登录淘美味
            </div>
            <a slot="right" @click='reg'>注册</a>
        </x-header>
        <!-- <x-hr></x-hr> -->
        <div class="main">
            <tab :line-width=2 v-model="index">
                <tab-item class="vux-center" :selected="delSel === item" v-for="(item, index) in list2" @click="delSel = item" :key="index">{{item}}</tab-item>
            </tab>

            <swiper v-model="index" height="250px" :show-dots="false">
                <!-- 手机登录 -->
                <swiper-item :key="0">
                    <div class="btn_wrap">
                        <group title="">
                            <x-input class="bg" title="+86" name="mobile" placeholder="请输入手机号码" v-model="phone" keyboard="number" is-type="china-mobile"></x-input>
                            <br/>
                            <div>
                                <x-input class="bg" placeholder="请输入验证码" v-model="captcha">
                                    <x-button slot="right" type="primary" action-type="button" mini @click.native="sendMessage">{{word}}</x-button>
                                </x-input>
                                <br/>
                            </div>
                        </group>
                        <x-button type="primary" action-type="button" @click.native="login(1)">登录</x-button>
                    </div>
                </swiper-item>

                <!-- 账号登录   //取消账号登录
                <swiper-item :key="1">
                    <div class="btn_wrap">
                        <group>
                            <x-input name="loginId" v-model="loginId" placeholder="请输入淘美味账号" ></x-input>
                            <x-input v-model="password" :type="this.registration_data.pwdType" placeholder="请输入密码"  @on-change="changePwd()">
                            　  <img  slot="right-full-height" class="registration" :src="this.registration_data.src" @click="changeType()"/>
                            </x-input>
                            <br/>
                            <x-button type="primary" action-type="button" @click.native="login(2)">登录</x-button>
                        </group>
                    </div>
                </swiper-item>-->
            </swiper>
            <div class="btn_wrap" v-show="iswxdl">
                <divider>OR</divider>
                <!-- wxLogin -->
                <x-button plain type="primary" style="border-radius:99px;" @click.native="wxLogin($event)">微信登录</x-button>
            </div>

        </div>

        <div>
            <loading :show="showLoading" text=""></loading>
        </div>
    </div>

</template>
    
<script>
import Vue from "vue";
import {
  Alert,
  XButton,
  GroupTitle,
  Group,
  XInput,
  XHr,
  XHeader,
  Loading,
  Tab,
  TabItem,
  Sticky,
  Divider,
  Swiper,
  SwiperItem,
  Confirm,
  TransferDomDirective as TransferDom
} from "vux";
import { ConfirmPlugin } from "vux";
import { sign, signStr } from "@/assets/js/sign.js";
import { hex_sha1 } from "@/assets/js/sha1.js";

import {  isWeiXin, getWXLoginUrl } from "@/assets/js/utils"; //获取url参数

Vue.use(ConfirmPlugin);

export default {
  directives: {
    TransferDom
  },
  components: {
    Alert,
    XButton,
    GroupTitle,
    Group,
    XInput,
    XHr,
    XHeader,
    Loading,
    Tab,
    TabItem,
    Sticky,
    Divider,
    Swiper,
    SwiperItem,
    Confirm
  },
  data() {
    return {
      showLoading: false,
      business: null,
      regUrl: "/URegister",
      // list2: ['手机登录', '账号登录'],  //取消账号登录
      list2: ["手机登录"],
      delSel: "手机登录",
      index: 0,
      loginId: "",
      password: "",
      phone: "",
      openid: "",
      captcha: "", //验证码
      registration_data: {
        //显示隐藏密码
        pwdType: "password",
        src: require("@/assets/img/colse_eyes.png")
      },
      word: "发送验证码",
      isOvertime: false,
      iswxdl: false,
      memberpt: null, //平台会员信息
      membersj: null, //商家会员信息
      memberurl: "", //微信授权登录后 跳转的地址
      localurl: "" //本页面URL
    };
  },
  mounted() {},
  beforeCreate() {
    this.localurl = decodeURIComponent(window.location.href); //保存本页URL
    localStorage.setItem("regUrl", this.localurl);
    this.memberurl = localStorage.getItem("memberurl");
  },
  created() {
    this.showLoading = true;
    // console.log(this.showLoading);
    
    this.memberpt = this.$store.state.memberInfoPt; 
    this.loginId = this.memberpt.bianh;
    // sessionStorage.getItem("loginId"); 
    this.phone = this.memberpt.dianh;
    // sessionStorage.getItem("phone");
    this.openid = this.memberpt.weixbh;
    // sessionStorage.getItem("openid"); 

    // console.log("openid: " + this.openid);

    if (this.openid != null && this.openid != "") {
      this.iswxdl = false;
    } else {
      this.iswxdl = true;
    }
    // console.log("iswxdl: " + this.iswxdl);

    // var binfo = localStorage.getItem("bInfo");
    // this.business = JSON.parse(binfo);
    this.business = this.$store.state.sellerInfo; 
    this.showLoading = false;
  },
  methods: {
    reg() {
      this.$router.push(this.regUrl);
    },
    login(index) {
      this.showLoading = true;
      // console.log(this.showLoading);
      let urlparam = sign("/v1/api/member/MemberLogin");
      urlparam.append("index", index);
      urlparam.append("loginname", this.loginId);
      urlparam.append("phone", this.phone);
      urlparam.append("password", hex_sha1(this.password));
      urlparam.append("captcha", this.captcha);
      urlparam.append("sjid", this.business.id);
      this.$http.post("member/MemberLogin", urlparam).then(ret => {
        if (ret.status == 200) {
          var _data = ret.data.resultObject;
          var _code = ret.data.code || ret.data.result.code;
          var _msg = ret.data.msg || ret.data.result.msg;

          if (_code == 1) {
            // sessionStorage.setItem("loginId", this.loginId);
            // sessionStorage.setItem("password", this.password);
            // sessionStorage.setItem("phone", this.phone);
            //存储平台会员信息
            // localStorage.setItem("memberpt", JSON.stringify(_data.pthyxx));
            this.$store.commit("addMemberInfoPt", _data.pthyxx);
            //存储商家会员信息
            // localStorage.setItem("membersj", JSON.stringify(_data.sjhycx));
            this.$store.commit("addMemberInfoSj", _data.sjhycx);

            this.$vux.toast.show({ text: "登录成功" });
            this.$router.push({
              name: "/Member",
              params: { openid: this.openid }
            });

            // this.memberpt = JSON.stringify(_data.pthyxx);
            // this.membersj = JSON.stringify(_data.sjhycx);

            // this.memberUrl = ''; //会员信息页面URL
            // this.memberInfo = this.memberpt.mingc; //会员昵称

            this.showLoading = false;
            return 1;
          } else {
            // this.memberUrl = '/?code=04a1ea60cc0550cc/#/ULogin'; //会员信息页面URL
            // this.memberInfo = '请点击登录/注册'; //会员昵称

            this.showLoading = false;
            this.$vux.toast.show({ type: "warn", text: _msg });
            return 0;
          }
        }
      });
      this.showLoading = false;
    },
    onItemClick(index) {
      // console.log("on item click:", index);
    },
    addTab() {
      if (this.list2.length < 5) {
        this.list2 = list().slice(0, this.list2.length + 1);
      }
    },
    removeTab() {
      if (this.list2.length > 1) {
        this.list2 = list().slice(0, this.list2.length - 1);
      }
    },
    next() {
      if (this.index === this.list2.length - 1) {
        this.index = 0;
      } else {
        ++this.index;
      }
    },
    prev() {
      if (this.index === 0) {
        this.index = this.list2.length - 1;
      } else {
        --this.index;
      }
    },
    changeType() {
      //显示隐藏密码
      this.registration_data.pwdType =
        this.registration_data.pwdType === "password" ? "text" : "password";
      this.registration_data.src =
        this.registration_data.src === require("@/assets/img/colse_eyes.png")
          ? require("@/assets/img/open_eyes.png")
          : require("@/assets/img/colse_eyes.png");
    },
    changePwd() {
      /*
                this.$vux.alert.show({
                    title: '提示',
                    content: 'Do you agree?',
                    onShow () {
                        console.log('Plugin: I\'m showing')
                    },
                    onHide () {
                        console.log('Plugin: I\'m hiding now')
                    }
                })*/
    },
    sendMessage() {
      if (this.phone == null || this.phone.trim() == "") {
        this.$vux.toast.show({ type: "text", text: "请输入手机号" });
        return;
      }

      if (this.isOvertime) {
        return false;
      }

      let that = this,
        time = 60;
      var sendTimer = setInterval(function() {
        that.isOvertime = true;
        time--;
        that.word = "重新发送(" + time + ")";
        if (time < 0) {
          that.isOvertime = false;
          clearInterval(sendTimer);
          that.word = "获取验证码";
        }
      }, 1000);

      this.sendCaptcha();
    },
    //发送验证码
    sendCaptcha() {
      let urlparam = sign("/v1/api/member/CaptchaSend");
      urlparam.append("type", 2);
      urlparam.append("phone", this.phone);

      this.$http
        .post("member/CaptchaSend", urlparam)
        .then(ret => {
          if (ret.status == 200) {
            var _data = ret.data.resultObject;
            var _code = ret.data.code || ret.data.result.code;
            var _msg = ret.data.msg || ret.data.result.msg;

            if (_code == 1) {
              this.$vux.toast.show({
                type: "text",
                text: "发送成功,5分钟内有效"
              });
            } else {
              this.$vux.toast.show({ type: "warn", text: _msg });
              return -1;
            }

            return 1;
          } else {
            this.$vux.toast.show({ type: "warn", text: ret.data.msg });
            return 0;
          }
        })
        .catch(err => {
          this.$vux.toast.show({ type: "warn", text: err.data.msg });
          return -1;
        });
    },
    //判断是否微信登陆 是不是微信浏览器
    // isWeiXin() {
    //     let ua = window.navigator.userAgent.toLowerCase();
    //     console.log('test: '+ua);
    //     if (ua.match(/MicroMessenger/i) == 'micromessenger') {
    //         console.log('weixin is true')
    //         return true;
    //     } else {
    //         this.$vux.alert.show({ title:'提示', content:'请使用微信客户端登录'} )
    //         console.log('weixin is false')
    //         return false;
    //     }
    // },
    wxLogin() {
      if (isWeiXin()) {
        window.location.href = getWXLoginUrl(
          encodeURIComponent(this.memberurl)
        );
        // window.location.href = "http://pay.gxmisi.com/v1/api/wxLogin";

        //微信登录，接口由后台定义
        // this.$http.get('http://testpay.gxmisi.com/ceshi1/wxget').then((res) => {
        //     if(res.data.code==0){   //微信登录成功跳转个人中心
        //         this.$router.push({ name:'Member' })
        //     }else{                //微信登录失败，使用填写信息登录
        //         this.$router.push({ name:'ULogin' })
        //     }
        // })
      } else {
        this.$vux.alert.show({
          title: "提示",
          content: "请使用微信客户端登录"
        });
      }
    }
  }
};
</Script>


<style scoped lang="less">
.ret {
  position: fixed;
  top: 0;
  width: 100%;
  height: 40px;
  z-index: 9999999;
  background-color: #fff;
}
.retTitle {
  color: #000;
  font-size: 14px;
}

.main {
  margin-top:40px; 
  width: 100%;
  height: 100%;
}

.inp {
  border: 1px;
}
.btn_wrap {
  margin: 0 auto;
  padding: 0 1rem;
  margin-top: 2rem;
  background-color: #fff;
}
.registration {
  width: 100%;
  height: 70%;
  margin-top: 0.5rem;
}

.bg {
  background-color: #f3f3f3;
}
</style>